<?php
require_once 'Zend/Db/Adapter/Pdo/Mysql.php';

class MySQLDataProvider extends DataProvider{
		var $db;
		function MySQLDataProvider($db_conf)
		{
			$this->db = new Zend_Db_Adapter_Pdo_Mysql($db_conf);
		}
		function get_events($datestart,$dateend,$type)
		{
			$db=&$this->db;
			$select = $db->select();
			$select->from(array('Event'=>'events'));
			$conditions = "(UNIX_TIMESTAMP(Event.start) <= $datestart AND UNIX_TIMESTAMP(Event.end) >= $datestart)"; // eventi che iniziano prima del periodo e finiscono dopo
			$conditions .=" OR (UNIX_TIMESTAMP(Event.start) >= $datestart  AND UNIX_TIMESTAMP(Event.start) <= $dateend)";
			//$conditions .=' AND user_id ='.$this->user_logged['id'];
			$select->where($conditions);
			$query = $db->query($select);
			$events = $query->fetchAll();	
			unset($conditions);
			return $events;
		}
		
		function get_repeated_events($datestart,$type){
			$db=&$this->db;
			$select = $db->select();
			$select->from(array('EventsRepeat'=>'repeated_events'),array('type','repeat_end','frequency','days','event_id'))
				->join(array('Event'=>'events'),'EventsRepeat.event_id = Event.id');
			// Scaricamenti eventi ripetuti
			$conditions = "UNIX_TIMESTAMP(EventsRepeat.repeat_end) > $datestart OR EventsRepeat.repeat_end is null";
			//$conditions .=' AND user_id ='.$this->user_logged['id'];

			$select->where($conditions);
			$query = $db->query($select);
			return $query->fetchAll();	
		}
		
		function get_event($event_id){
			$db=&$this->db;
			$select = $db->select();
			$select->from('events',array('id','start','end'));				
			$select->where('id = ?',$event_id);
			$query = $db->query($select);
			$event = $query->fetchAll();	
			return $event[0];
		}
		function update_event($data,$event_id){
			$this->db->update('events',$data,$this->db->quoteInto('id = ?',$event_id));
		}
		function delete_event($event_id){
			$this->db->delete('events','id='.$this->db->quote($event_id));
		}
		function insert_event($data){
			$this->db->insert('events',$data);
			$event_id=$this->db->lastInsertId();
			return $event_id;
		}
		function delete_event_repeat($event_id){
			$result = $this->get_event_repeat($event_id);
			if($result) $this->delete_repeated_events($event_id);
			$this->db->delete('repeated_events',$this->db->quoteInto('event_id = ?',$event_id));	
		}
		function get_event_repeat($event_id){
			return $this->db->fetchRow('SELECT id FROM repeated_events WHERE event_id='.$this->db->quote($event_id));
		}
		function update_event_repeat($data,$event_id)
		{
			$this->db->update('repeated_events',$data,$this->db->quoteInto('event_id = ?',$event_id));
		}
		function insert_event_repeat($data){
			$this->db->insert('repeated_events',$data);
		}
		
			
	}
?>